//
//  AuthPlugin.swift
//  SwiftProject
//
//  Created by 董駸 on 2022/7/28.
//

import Moya

/// 用于授权插件
class AuthPlugin: PluginType {
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        // print("prepare")
        var mRequest = request
        // 判断该请求是否需要授权
        guard let target = target as? MyService, target.needsAuth else {
            return mRequest
        }
        // 将token添加到请求头中
        mRequest.addValue("token", forHTTPHeaderField: "Authorization")
        return mRequest
    }
    
    func willSend(_ request: RequestType, target: TargetType) {
        //print("开始请求")
    }
    
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        //print("结束请求")
    }
}
